package com.lsmgc.cms.servlet;

import com.alibaba.fastjson.JSON;
import com.lsmgc.cms.entity.user.User;
import com.lsmgc.cms.util.ServletUtils;
import com.lsmgc.cms.util.json.JsonReulst;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

public class AdminServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String path = request.getServletPath();
        switch (path) {
            case "/admin/login":
                login(request, response);
                break;
            case "/admin/index":
                index(request, response);
                break;
            case "/admin/ajax/login":
                ajaxLogin(request, response);
                break;
            case "/admin/ajax/logout":
                ajaxLogout(request, response);
                break;
        }
    }

    /**
     * 管理员登录
     * @param request
     * @param response
     */
    private void login(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.getRequestDispatcher(ServletUtils.getJspPage("admin/admin-login")).forward(request, response);
    }

    /**
     * 管理员首页
     * @param request
     * @param response
     */
    private void index(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.getRequestDispatcher(ServletUtils.getJspPage("admin/admin-index")).forward(request, response);
    }

    /**
     * 管理员登录
     * @param request
     * @param response
     */
    private void ajaxLogin(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String name = request.getParameter("name");
        String password = request.getParameter("password");
        if ("admin".equals(name) && "admin123".equals(password)) {
            ServletUtils.renderJson(response, ServletUtils.getYesJson());
        } else {
            ServletUtils.renderJson(response, ServletUtils.getNoJson());
        }
    }

    /**
     * 管理员退出
     * @param request
     * @param response
     */
    private void ajaxLogout(HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.setContentType("text/html;charset=utf-8");
        PrintWriter writer = response.getWriter();
        writer.write(JSON.toJSONString(JsonReulst.yes()));
    }
}